package wortubung.quiz;

import java.util.HashMap;

import wortubung.core.MEANING;
import wortubung.core.WORD;
import wortubung.util.CommonUtils;

public class CrossMatchingSuite {
	HashMap<String,String> pairs = new HashMap<String,String>();
	String[] leftTexts;
	String[] rightTexts;
	Integer[] answers;
	int maxLeftLength = 6;

	public void add(String left, String right) {
		for (String x : pairs.values()) {
			if (x.equals(right))
				return;
		}

		if (left.length() > maxLeftLength)
			maxLeftLength = left.length();
		pairs.put(left, right);
	}

	public void add(WORD word) {
		MEANING def = word.getDefinitionForTest();
		if (def != null)
			add(word.getWord(), def.getMeaning());
	}

	public void reset() {
		pairs.clear();
		leftTexts = null;
		rightTexts = null;
		answers = null;
	}

	public int size() {
		if (answers == null)
			generate();
		return CommonUtils.length(answers);
	}
	public String getLeft(int idx) { return leftTexts[idx]; }
	public String getRight(int idx) { return rightTexts[idx]; }
	public int getAnswer(int idx) { return answers[idx]; }
	public int getMaxLeftLength() { return maxLeftLength; }

	private void generate() {
		int i;
		int size = pairs.size();
		leftTexts = pairs.keySet().toArray(new String[size]);
		rightTexts = new String[size];
		answers = new Integer[size];
		for (i=0; i<size; ++i)
			answers[i] = i;
		CommonUtils.randomize(answers);
		for (i=0; i<size; ++i)
			rightTexts[answers[i]] = pairs.get(leftTexts[i]);
	}
}
